package com.zxh.filters;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.HashMap;
import java.util.TreeSet;

@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {

    //将所有请求放在map中记录请求时间
    public static HashMap<String, TreeSet<TPsion>> requestTpsion = new HashMap<String, TreeSet<TPsion>>();

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long  startTime  = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long endTime  = System.currentTimeMillis();
        String key = invocation.getServiceName() + ":" + invocation.getMethodName();
        synchronized (requestTpsion) {
            TreeSet<TPsion> treeSet = requestTpsion.get(key);
            if(treeSet == null) {
                treeSet = new TreeSet<TPsion>();
                requestTpsion.put(key, treeSet);
            }
            treeSet.add(new TPsion(endTime - startTime, startTime));
        }

        return result;
    }


    public static class TPsion implements Comparable<TPsion> {
        public long sendTime;  //请求时间， 毫秒
        public long spendTime; //请求耗时， 毫秒

        public TPsion(long spendTime, long sendTime) {
            this.sendTime  = sendTime;
            this.spendTime = spendTime;
        }

        @Override
        public int compareTo(TPsion o) {
            if(spendTime == o.spendTime) {
                return 0;
            } else if(spendTime < o.spendTime) {
                return -1;
            } else {
                return 1;
            }
        }
    }
}
